package com.njit.postbar.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;

public class HTML {
    private static final String ERROR = "ERROR";
    /**
     *@author yuruiqiao
     *@date 2020/5/27
     *@description 设置头像的URL,背景色,圆角
     *@param url  完整的网络图片地址
     *@param bgColor  "#ffffff" or "rgb(r, g, b)";
     *@param radius  设置头像四个角的曲率,0-50%
     */
    public static String setImage(String url,String bgColor,String radius){
        String str = read("/assets/headImage.html");
        if(!str.equals(ERROR)){
            str = str.replaceAll("####",url);
            str = str.replaceAll("###",bgColor);
            str = str.replaceAll("##",radius);
            return str;
        }
        return ERROR;
    }

    /**
     *@author yuruiqiao
     *@date 2020/6/03
     *@description 设置详情页内容
     *@param content  完整的网络图片地址
     */
    public static String setDESC(String content){
        String str = read("/assets/content.html");
        if(!str.equals(ERROR)){
            str = str.replaceAll("####", Matcher.quoteReplacement(content));
            return str;
        }
        return ERROR;
    }

    /**
     *@author yuruiqiao
     *@date 2020/5/27
     *@description 读操作
     *@param template 模板文件路径
     */
    private static String read(String template){
        InputStream is = HTML.class.getResourceAsStream(template);
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            assert is != null;
            int index = is.read();
            while(index != -1) {
                bo.write(index);
                index = is.read();
            }
            //将字符串中的$符号进行正规化处理
            return java.util.regex.Matcher.quoteReplacement(bo.toString());
        } catch (IOException e) {
            return ERROR;
        }
    }
}
